#!/usr/bin/env python
#-*- coding:UTF-8 -*-
#####################################################
# Author: Jiaion - jiaion21@gmail.com
# Last modified:	2011-04-23 16:14
# Filename:	main.py
#####################################################
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from Context.Render import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth import logout
from django.utils import simplejson
from django.conf import settings
from Jiaion.models import REG
import Jredis as redis
import re
import random

def Login(request):
    if request.method == 'POST':
        try:
            Pwd = request.REQUEST.get('pwd').encode('utf-8')
            Loguser = request.REQUEST.get('log').encode('utf-8')
        except :
            return render('Login.html',{'error':'用户名或密码不能为空',},request)
        if Pwd and Loguser:
            user = authenticate(username=Loguser, password=Pwd)
            if user is not None:
                login(request,user)
                Username = request.user.username
                Next = re.search(r"=/(\w+)/", request.get_full_path())
                if Next:
                    Next = Next.group(1)
                else:
                    Next = "index"
                return HttpResponseRedirect("/%s" % Next)
            else:
                return render('Login.html',{'error':'用户名或密码错误',},request)
        else:
            return render('Login.html',{'error':'用户名或密码不能为空',},request)
    else:
        return render('Login.html',{},request)


def _Randstr(len):
    return ''.join(random.sample([chr(i) for i in range(48, 123)], len))

def Userreg(request):
    if request.method == 'POST':
        USERNAME = request.REQUEST.get('user')
        CHUSERNAME = request.REQUEST.get('chuser')
        Org = request.REQUEST.get('org')
        if USERNAME and CHUSERNAME and Org:
            USERPASS = _Randstr(8)
            if REG.objects.filter(USER=USERNAME):
                return render('userreg.html',{'Exist':True,},request)
            REGUSER = REG(USER=USERNAME,CHUSER=CHUSERNAME,PASS=USERPASS,ORG=Org,APPROVAL=0)
            REGUSER.save()
            value = {'ToList':['zheng.jia@rekoo.com',], 'Mail':u'有新用户申请', 'UserName':USERNAME, 'Type':'SendAdm'}
            redis.lpushs("USERREG",value)
            return render('userreg.html',{'DONE':True,},request)
        return render('userreg.html',{'ERROR':True,},request)
    return render('userreg.html',{},request)

@login_required()
def index(request):
    return render('index.html',{},request)

def Logout(request):
  logout(request)
  return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
